package com.kerrykidz.sales.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kerrykidz.common.Constants;
import com.kerrykidz.common.ORDER_CONSTANTS;
import com.kerrykidz.dao.model.GblPosDiscountEntity;
import com.kerrykidz.parreserve.dao.model.ParReserveEntity;
import com.kerrykidz.parreserve.service.IParReserveService;
import com.kerrykidz.sales.dao.model.PosOrderEntity;
import com.kerrykidz.sales.dao.model.PosOrderPrdEntity;
import com.kerrykidz.sales.service.IOrderService;
import com.kerrykidz.scminvoicing.dao.model.GblScmPrdCateEntity;
import com.kerrykidz.scminvoicing.dao.model.GblScmPrdEntity;
import com.kerrykidz.scminvoicing.dao.model.ScmPrdStgEntity;
import com.kerrykidz.scminvoicing.service.IScmInvocingProductInfoService;
import com.kerrykidz.scmstock.service.IStockGoodsInService;
import com.kerrykidz.system.util.UserUtil;
import com.kerrykidz.system.vo.UserInfo;
import com.rdp.framework.exception.RDPException;

/**
 * 
 * @Description 商品相关操作
 * @author QUINN
 * @date 2014年8月21日下午1:27:29
 */
@Controller
@RequestMapping("goods")
public class GoodsController {

	@Autowired
	private IScmInvocingProductInfoService scmInvocingProductInfoService;

	@Autowired
	private IParReserveService parReserveService;

	@Autowired
	private IStockGoodsInService stockGoodsInService;

	@Autowired
	private IOrderService orderService;

	// 商品列表页面
	@RequestMapping(value = "list")
	public String list(HttpSession session, ModelMap model) {
		String branId = UserUtil.getUserFromSession().getBranId();
		List<ParReserveEntity> reserves = this.parReserveService.findParReserve(branId,Constants.RESERVE_STATUS_PROCEEDING, "0");

		// 查找的一购物车
		String shopCartId = (String) session.getAttribute(ORDER_CONSTANTS.CURRENT_ORDER_ID);
		model.put("reserves", reserves);
		if (shopCartId != null)
			model.put("shopCartId", shopCartId);
		return "goods/list";
	}

	// 分页查询商品数据
	@RequestMapping(value = "paginate", method = RequestMethod.POST)
	@ResponseBody
	public GblScmPrdEntity paginate(GblScmPrdEntity pagebean) {
		try {
			pagebean.setFkBranId(UserUtil.getUserFromSession().getBranId());
			pagebean = this.scmInvocingProductInfoService.paginateGoods(pagebean);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return pagebean;
	}

	// 添加商品到订单
	@RequestMapping(value = "put2Order", method = RequestMethod.POST)
	@ResponseBody
	public String put2Order(@RequestParam("isParty") boolean isParty,
			@RequestParam("partyId") String partyId,
			@RequestParam("productId") String productId,
			@RequestParam("shopCartId") String shopCartId,
			@RequestParam("count") int count, HttpSession session) {

		PosOrderEntity order;

		UserInfo user = UserUtil.getUserFromSession();

		String orderId;
		session.setAttribute("isParty", isParty);

		// 如果是派对
		if (isParty) {
			order = new PosOrderEntity();
			// 根据排队查找订单
			order.setFkParresId(partyId);
			order = this.orderService.findByCondition(order);
			orderId = order.getPkOrderId();
		} else// 非派对找购物车
		{
			// 先判断是否有购物车
			if (StringUtils.isBlank(shopCartId)
					&& (shopCartId = (String) session
							.getAttribute(ORDER_CONSTANTS.CURRENT_ORDER_ID)) == null) {
				order = this.orderService.createAndfindCurrentShopCart(
						user.getUserId(), user.getAbbrCode(), user.getBranId());
				orderId = order.getPkOrderId();
			} else
				orderId = shopCartId;
		}
		// 当前的POS_ORDER ID
		session.setAttribute(ORDER_CONSTANTS.CURRENT_ORDER_ID, orderId);

		// 再检查该订单内是否已经存在该商品
		PosOrderPrdEntity prd = new PosOrderPrdEntity();
		prd.setPkOrderId(orderId);
		prd.setFkPrdId(productId);
		prd = this.orderService.findOrderPrdByCondition(prd);

		/*
		 * 一定要更新掉当前商品的价格
		 */
		GblScmPrdEntity product;
		try {
			// 先查询该商品的价格
			product = this.scmInvocingProductInfoService.getProductById(
					productId, user.getBranId());
		} catch (RDPException e) {
			product = null;
			e.printStackTrace();
		}

		if (prd == null)// 如果商品明细为空，需要创建商品明细
		{

			List<PosOrderPrdEntity> prds = new ArrayList<PosOrderPrdEntity>();
			PosOrderPrdEntity p = new PosOrderPrdEntity();
			p.setPkOrderId(orderId);
			p.setFkPrdId(productId);
			p.setCount(count);
			double price = product.getProductPrice()
					* (product.getDisValue() == null
							|| product.getDisValue() == 0 ? 1d : product
							.getDisValue());
			p.setPrice(price);
			p.setDisPrice(price);
			prds.add(p);
			try {
				// 创建商品明细
				this.orderService.createOrderPrd(prds);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else// 如果存在商品 修改商品数量
		{
			prd.setCount(prd.getCount() + count);
			prd.setPrice(product.getProductPrice());
			try {
				this.orderService.updateOrderProduct(prd);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return orderId;
	}

	@RequestMapping(value = "modifyGoodsStgCnt", method = RequestMethod.POST)
	@ResponseBody
	public boolean modifyGoodsStgCnt(@RequestParam("orderId") String orderId,
			@RequestParam("productId") String productId,
			@RequestParam("count") int count) {
		ScmPrdStgEntity scmPrdStg = new ScmPrdStgEntity();
		scmPrdStg.setInstgCnt(count);
		scmPrdStg.setFkPrdId(productId);
		scmPrdStg.setFkBranId(UserUtil.getUserFromSession().getBranId());

		if (StringUtils.isNotBlank(orderId)) {
			PosOrderPrdEntity prd = new PosOrderPrdEntity();
			prd.setPkOrderId(orderId);
			prd.setFkPrdId(productId);

			PosOrderPrdEntity p = this.orderService.findOrderPrdByCondition(prd);
			prd.setCount(p.getCount() - count);
			try {
				this.orderService.updateOrderProduct(prd);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			this.stockGoodsInService.updateScmPrdStg(scmPrdStg);
			return true;
		} catch (RDPException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@RequestMapping(value = "removeOrderPrd", method = RequestMethod.POST)
	@ResponseBody
	public boolean removeOrderPrd(@RequestParam("orderId") String orderId,
			@RequestParam("productId") String productId) {
		this.orderService.removeOrderPrdByOrderIdAndProductId(orderId,
				productId);
		return true;
	}

	@RequestMapping(value = "padSales")
	public String padSales(String cateId, ModelMap model, HttpSession session) {
		UserInfo user = UserUtil.getUserFromSession();
		try {
			List<GblScmPrdCateEntity> higherCates = this.scmInvocingProductInfoService.recurseCate(cateId, true, false);
			model.put("higherCates", higherCates);
			GblScmPrdCateEntity c = higherCates.get(higherCates.size() - 1);
			model.put("cate", c);
			GblScmPrdCateEntity entity = new GblScmPrdCateEntity();
			entity.setFkParPrdcateId(c.getPkPrdcateId());
			entity.setParPkSelect(true);
			entity.setSales(true);
			
			List<GblScmPrdCateEntity> cates = this.scmInvocingProductInfoService.findCategoryList(entity);
			model.put("lowerCates", cates);
			List<ParReserveEntity> reserves = this.parReserveService.findParReserve(user.getBranId(),
					Constants.RESERVE_STATUS_PROCEEDING, "0");
			model.put("reserves", reserves);
			// 查找购物车
			String shopCartId = (String) session.getAttribute(ORDER_CONSTANTS.CURRENT_ORDER_ID);
			model.put("shopCartId", shopCartId);
			List<GblPosDiscountEntity> discounts = this.scmInvocingProductInfoService.findAllDiscount();
			model.put("discounts", discounts);
			model.put("user", user);
		} catch (RDPException e) {
			e.printStackTrace();
		}

		return "goods/padList";
	}

	@RequestMapping(value = "validGiftno", method = RequestMethod.POST)
	@ResponseBody
	public boolean validGiftno(@RequestParam("id") String id) {
		return this.orderService.validaGiftno(id);
	}

	@RequestMapping(value = "buyGiftNo", method = RequestMethod.POST)
	@ResponseBody
	public boolean buyGiftNo(@RequestParam("id") String id, @RequestParam("no") String no,
			@RequestParam("price") Double price, HttpSession session) {
		String shopCartId = (String) session.getAttribute(ORDER_CONSTANTS.CURRENT_ORDER_ID);
		UserInfo user = UserUtil.getUserFromSession();
		String orderId;
		if (StringUtils.isBlank(shopCartId)) {
			PosOrderEntity order = new PosOrderEntity();
			order.setOrderStatus(ORDER_CONSTANTS.ORDER_STATUS_SHOPCART);
			String userid = user.getUserId();
			order.setFkOperator(userid);
			order = this.orderService.findByCondition(order);
			if (order == null)
				order = this.orderService.createAndfindCurrentShopCart(user.getUserId(), user.getAbbrCode(),
						user.getBranId());
			orderId = order.getPkOrderId();
			session.setAttribute(ORDER_CONSTANTS.CURRENT_ORDER_ID, orderId);
		} else
			orderId = shopCartId;

		List<PosOrderPrdEntity> prds = new ArrayList<PosOrderPrdEntity>();
		PosOrderPrdEntity p = new PosOrderPrdEntity();
		p.setPkOrderId(orderId);
		p.setFkPrdId(id);
		p.setCount(1);
		p.setGiftNo(no);
		p.setPrice(price);
		p.setDisPrice(price);
		prds.add(p);
		try {
			// 创建商品明细
			this.orderService.createOrderPrd(prds);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@RequestMapping(value = "setParty", method = RequestMethod.POST)
	public void setParty(@RequestParam("isParty") Boolean isParty, @RequestParam("patryId") String patryId,
			HttpSession session) {
		session.setAttribute("isParty", isParty);
		if (isParty)
			session.setAttribute("shopCartId", patryId);
		else
			session.removeAttribute("shopCartId");
	}
}
